package com.wang.service.impl;

import com.wang.entity.Cart;
import com.wang.entity.Product;
import com.wang.mapper.CartMapper;
import com.wang.mapper.ProductMapper;
import com.wang.service.CartService;
import com.wang.utils.ResponseEnum;
import com.wang.utils.ResponseUtil;
import com.wang.vo.CartVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname CartServiceImpl
 * @Description TODO
 * @Date 2025/3/24 10:52
 * @Created by pc
 */
@Service
@Transactional
public class CartServiceImpl implements CartService {
    @Resource
    private CartMapper cartMapper;
    @Resource
    private ProductMapper productMapper;

    @Override
    public ResponseUtil findCount(Integer userId) {
        Integer count = cartMapper.findCountByUserId(userId);
        return ResponseUtil.get(ResponseEnum.CART_FIND_COUNT,count);
    }

    @Override
    public ResponseUtil findCartByUserId(Integer userId) {
        List<Cart> cartList = cartMapper.findCartByUserId(userId);

        // 每查询一个购物车 应该去查询商品详情 封装Vo
        List<CartVo> cartVoList = new ArrayList<>();
        cartList.forEach(cart -> {
            Integer productId = cart.getProductId();
            Product product = productMapper.findById(productId);
            CartVo cartVo = new CartVo();
            BeanUtils.copyProperties(cart,cartVo);
            cartVo.setPrice(new BigDecimal(product.getPrice()));
            cartVo.setName(product.getName());
            cartVoList.add(cartVo);
        });
        ResponseUtil r =  ResponseUtil.get(ResponseEnum.CART_FIND_CART_INFO,cartVoList);
        return r;
    }

    @Override
    public ResponseUtil updateCart(Integer id, Integer quantity, Integer checked) {
        Integer result = cartMapper.updateCart(id,quantity,checked);
        return result.intValue() > 0 ?
                ResponseUtil.get(ResponseEnum.CART_UPDATE_CART_SUCCESS)
                :ResponseUtil.get(ResponseEnum.CART_UPDATE_CART_FAILURE);
    }
}
